<template>
  <div>
    <!-- 设置市场价 -->
    <el-dialog
      v-el-drag-dialog
      :title="type === 'current' ? '设置本期市场价' : '设置下期市场价'"
      :visible.sync="visible"
      width="800px"
      @closed="reset"
    >
      <div class="center">
        <!-- 描述列表 -->
        <el-descriptions size="medium" style="margin-top: 10px; margin-bottom: 20px;">
          <el-descriptions-item label="编码">{{ temp.goodsCode }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ temp.goodsName }}</el-descriptions-item>
          <el-descriptions-item label="类别">{{ temp.gtName }}</el-descriptions-item>
        </el-descriptions>

        <!-- 总公司定价 -->
        <div class="item">
          <el-form ref="dataForm" class="form" :model="temp" :rules="rules" label-position="right" label-width="90px">
            <el-form-item label="周期编号:" prop="cycNumber">
              <el-input v-model="temp.cycNumber" :maxlength="15" :disabled="type === 'current'" clearable />
            </el-form-item>
            <div class="title block">
              <span class="title-icon" />
              <span class="title-text">呼叫中心定价</span>
            </div>
            <el-form-item label="挂牌价:" prop="phonePrice.price0">
              <el-input-number v-model="temp.phonePrice.price0" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="居民价:" prop="phonePrice.price1">
              <el-input-number v-model="temp.phonePrice.price1" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="商业价:" prop="phonePrice.price2">
              <el-input-number v-model="temp.phonePrice.price2" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="工业价:" prop="phonePrice.price3">
              <el-input-number v-model="temp.phonePrice.price3" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100%;" />
            </el-form-item>
            <div class="title block">
              <span class="title-icon" />
              <span class="title-text">微信定价</span>
            </div>
            <el-form-item label="挂牌价:" prop="wxPrice.price0">
              <el-input-number v-model="temp.wxPrice.price0" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="居民价:" prop="wxPrice.price1">
              <el-input-number v-model="temp.wxPrice.price1" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="商业价:" prop="wxPrice.price2">
              <el-input-number v-model="temp.wxPrice.price2" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="工业价:" prop="wxPrice.price3">
              <el-input-number v-model="temp.wxPrice.price3" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100%;" />
            </el-form-item>
            <el-form-item v-if="type === 'next'" label="生效时间:" prop="startDt">
              <el-date-picker
                v-model="temp.startDt"
                type="datetime"
                unlink-panels
                placeholder="选择日期时间"
              />
            </el-form-item>
          </el-form>

          <el-descriptions v-if="type === 'current'" size="medium" style="margin-top: 20px; margin-bottom: 20px;">
            <el-descriptions-item label="生效时间"><span style="color: green;">即时生效</span></el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">
          关闭
        </el-button>
        <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { queryMarketPriceDefault, saveMarketPrice } from '@/api'
  import moment from 'dayjs'

  export default {
    name: 'currentPriceEdit',
    data() {
      const validateCycNumber = (rule, value, callback) => {
        if (value !== '') {
          if (value.length > 15) {
            callback(new Error('周期号最大长度为15'))
            return
          }
          const reg = /^[\w\-]{1,}$/
          if (!reg.test(value)) {
            callback(new Error('周期号必须为数字,字母,-'))
          }
        }
        callback()
      }
      return {
        visible: false,
        type: 'current',
        temp: {
          cycNumber: '',
          startDt: moment(),
          type: 0,
          isEdit: true,
          phonePrice: {
            price0: undefined,
            price1: undefined,
            price2: undefined,
            price3: undefined
          },
          wxPrice: {
            price0: undefined,
            price1: undefined,
            price2: undefined,
            price3: undefined
          }
        },
        rules: {
          cycNumber: [{ validator: validateCycNumber, trigger: 'blur' }],
          startDt: [{ required: true, message: '请输入生效时间', trigger: 'change' }]
        }
      }
    },
    methods: {
      open(temp, type) {
        console.log(temp)
        this.type = type
        this.temp.type = type === 'current' ? 0 : 1
        this.getDefaultData(temp)
        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
          }
        })
      },
      async getDefaultData(temp) {
        const res = await queryMarketPriceDefault({
          type: this.temp.type,
          goodsId: temp.goodsId
        })
        console.log(res.data, '-------------')
        const type1 = res.data.find(item => item.fromPlat === 1)
        const type2 = res.data.find(item => item.fromPlat === 2)
        const r = {
          cycNumber: res.data[0] ? res.data[0].cycNumber : moment(new Date()).format('YYYYMMDD-HHmm'),
          phonePrice: type1 ? { ...type1 } : { ...type2 },
          wxPrice: type2 ? { ...type2 } : { ...type1 }
        }
        this.temp = Object.assign(this.temp, r)
        console.log(r, this.temp)
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          if (((this.temp.phonePrice.price1 !== undefined && this.temp.phonePrice.price1 >= 0) || (this.temp.phonePrice.price2 !== undefined && this.temp.phonePrice.price2 >= 0)) && !(this.temp.phonePrice.price0 !== undefined && this.temp.phonePrice.price0 >= 0)) {
            this.$message.warning('请输入呼叫中心挂牌价')
            return
          }
          if (((this.temp.wxPrice.price1 !== undefined && this.temp.wxPrice.price1 >= 0) || (this.temp.wxPrice.price2 !== undefined && this.temp.wxPrice.price2 >= 0)) && !(this.temp.wxPrice.price0 !== undefined && this.temp.wxPrice.price0 >= 0)) {
            this.$message.warning('请输入微信挂牌价')
            return
          }
          if (!(this.temp.phonePrice.price0 !== undefined && this.temp.phonePrice.price0 >= 0) && !(this.temp.wxPrice.price0 !== undefined && this.temp.wxPrice.price0 >= 0)) {
            this.$message.warning('请输入挂牌价')
            return
          }
          const params = [{
            areaPriceId: this.temp.phonePrice.areaPriceId || 0,
            price0: this.temp.phonePrice.price0,
            price1: this.temp.phonePrice.price1,
            price2: this.temp.phonePrice.price2,
            price3: this.temp.phonePrice.price3,
            fromPlat: 1,
            cycNumber: this.temp.cycNumber,
            startDt: this.temp.type === 0 ? new Date() : moment(this.temp.startDt)
          }, {
            areaPriceId: this.temp.wxPrice.areaPriceId || 0,
            price0: this.temp.wxPrice.price0,
            price1: this.temp.wxPrice.price1,
            price2: this.temp.wxPrice.price2,
            price3: this.temp.wxPrice.price3,
            fromPlat: 2,
            cycNumber: this.temp.cycNumber,
            startDt: this.temp.type === 0 ? new Date() : moment(this.temp.startDt)
          }]
          for (const i in params) {
            const item = params[i]
            for (const k in item) {
              if (item[k] === undefined || item[k] === null || item[k] === '') {
                delete item[k]
              }
            }
          }
          this.submit(params)
        })
      },
      async submit(params) {
        await saveMarketPrice({
          mode: this.temp.type,
          goodsId: this.temp.goodsId,
          json: params
        })
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      },
      limitInput(value, name1, name2) {
        const str = (value && value.split('')) || []
        const reg1 = /\d/
        const reg2 = /\./
        // 第一个字符不能为小数点
        if (str[0] === '.') {
          this.temp[name1][name2] = ''
          return
        }
        // 过滤掉除数字和小数点外的字符
        value = str.filter(e => reg1.test(e) || reg2.test(e))
        // 匹配小数点后只能有两位小数
        const valJoin = value.join('')
        const res = valJoin.match(/^\d*(\.\d{0,2})/g)[0]
        this.temp[name1][name2] = res || null
      },
      onInput(value, name1, name2) {
        const res = value
          .replace(/[^\d.]/g, '')
          .replace(/\.{2,}/g, '.')
          .replace(/^\./g, '')
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.')
          .replace(/^0\d+|^\./g, '')
          .replace(/^(.*\..{2}).*$/, '$1')
        this.temp[name1][name2] = res
      },
      formatInput(e, name1, name2) {
        if (e.target.value) {
          this.temp[name1][name2] = Number(e.target.value).toFixed(2)
        }
      },
      reset() {
        this.type = 'current'
        this.temp = {
          cycNumber: '',
          startDt: moment(),
          type: 0,
          isEdit: true,
          phonePrice: {
            price0: undefined,
            price1: undefined,
            price2: undefined,
            price3: undefined
          },
          wxPrice: {
            price0: undefined,
            price1: undefined,
            price2: undefined,
            price3: undefined
          }
        }
      }
    }
  }
</script>

<style lang='scss' scoped>
.center {
  height: 500px;
  font-size: 14px;
  font-weight: 400;
  color: #333;
  text-align: left;
}

.item {
  margin-bottom: 30px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 16px;
      font-weight: 700;
      color: #01999f;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .content {
    margin-bottom: 30px;
  }
}

.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 50%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
